/* eslint-disable */
<template>
  <div class="map-container">
    <!-- 全局等待提示 -->
    <transition name="waiting-fade" mode="out-in">
      <div v-if="isWaiting" class="waiting-overlay">
        <div class="waiting-content">
          <div class="waiting-spinner">
            <div class="spinner-ring"></div>
            <div class="spinner-ring"></div>
            <div class="spinner-ring"></div>
          </div>
          <div class="waiting-text">{{ waitingText }}</div>
          <div class="waiting-progress">
            <div class="progress-bar" :style="{ width: progressPercent + '%' }"></div>
          </div>
        </div>
      </div>
    </transition>

    <!-- 加载状态 -->
    <transition name="loading-fade" mode="out-in">
      <div v-if="isLoading" class="map-loading">
        <div class="loading-spinner">
          <div class="wave-spinner">
            <div class="wave-ring wave-1"></div>
            <div class="wave-ring wave-2"></div>
            <div class="wave-ring wave-3"></div>
            <div class="wave-ring wave-4"></div>
            <div class="loading-text">加载中</div>
          </div>
        </div>
      </div>
    </transition>

    <div ref="mapContainer" class="map-inner"></div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { mapConfig } from '../config/map.config';

const mapContainer = ref(null);
const isLoading = ref(true);
const map = ref(null); // 地图实例
const markers = ref([]); // 标记点数组
const paths = ref([]); // 路径数组
const polygons = ref([]); // 多边形范围数组
const searchService = ref(null); // 搜索服务实例

// 等待提示相关变量
const isWaiting = ref(false);
const waitingText = ref('');
const progressPercent = ref(0);

// 显示等待提示
const showWaiting = (text = '处理中...', duration = 3000) => {
  isWaiting.value = true;
  waitingText.value = text;
  progressPercent.value = 0;

  // 模拟进度条
  const interval = setInterval(() => {
    if (progressPercent.value < 90) {
      progressPercent.value += Math.random() * 10;
    }
  }, 100);

  // 自动隐藏
  setTimeout(() => {
    hideWaiting();
    clearInterval(interval);
  }, duration);
};

// 隐藏等待提示
const hideWaiting = () => {
  isWaiting.value = false;
  progressPercent.value = 0;
};

// 地图初始化函数
const initMap = () => {
  if (mapContainer.value) {
    // 根据官方文档创建地图实例
    map.value = new TMap.Map(mapContainer.value, {
      center: new TMap.LatLng(mapConfig.DEFAULT_CENTER.lat, mapConfig.DEFAULT_CENTER.lng),
      zoom: mapConfig.MAP_OPTIONS.zoom,
      pitch: mapConfig.MAP_OPTIONS.pitch,
      rotation: mapConfig.MAP_OPTIONS.rotation,
      viewMode: mapConfig.MAP_OPTIONS.viewMode,
      mapStyleId: mapConfig.MAP_OPTIONS.mapStyleId,
      // 添加官方文档推荐的配置
      minZoom: mapConfig.MAP_OPTIONS.minZoom,
      maxZoom: mapConfig.MAP_OPTIONS.maxZoom,
      scrollWheel: mapConfig.MAP_OPTIONS.scrollWheel,
      doubleClickZoom: mapConfig.MAP_OPTIONS.doubleClickZoom,
      keyboardEnable: mapConfig.MAP_OPTIONS.keyboardEnable,
      draggable: mapConfig.MAP_OPTIONS.draggable
    });

    // 地图加载完成后隐藏loading
    map.value.on('load', () => {
      console.log('地图加载完成事件触发');
      isLoading.value = false;
      // 延迟初始化搜索服务，确保所有API都加载完成
      setTimeout(() => {
        initSearchService();
      }, 1000);
    });

    // 如果地图加载事件没有触发，延迟隐藏loading
    setTimeout(() => {
      console.log('地图加载超时，强制初始化');
      isLoading.value = false;
      if (map.value) {
        // 延迟初始化搜索服务
        setTimeout(() => {
          initSearchService();
        }, 1000);
      }
    }, 3000);
  }
};

// 动态加载腾讯地图SDK
const loadMapSDK = () => {
  const script = document.createElement('script');
  script.src = `https://map.qq.com/api/gljs?v=1.exp&key=${mapConfig.TENCENT_MAP_KEY}`;
  script.onload = () => {
    initMap();
  };

  script.onerror = () => {
    console.error('地图SDK加载失败');
    isLoading.value = false;
  };

  document.head.appendChild(script);
};

onMounted(() => {
  loadMapSDK();
});

// 地区搜索功能
const initSearchService = () => {
  console.log('=== 初始化搜索服务 ===');
  console.log('TMap对象:', window.TMap);
  console.log('TMap.service:', window.TMap?.service);
  console.log('地图实例:', map.value);

  // 检查TMap和搜索服务是否可用
  if (!window.TMap) {
    console.warn('TMap对象未加载，延迟初始化搜索服务');
    setTimeout(initSearchService, 1000);
    return;
  }

  if (!window.TMap.service || !window.TMap.service.Search) {
    console.warn('TMap搜索服务未加载，延迟初始化搜索服务');
    setTimeout(initSearchService, 1000);
    return;
  }

  if (!map.value) {
    console.warn('地图实例未初始化，延迟初始化搜索服务');
    setTimeout(initSearchService, 1000);
    return;
  }

  try {
    searchService.value = new TMap.service.Search({
      key: mapConfig.TENCENT_MAP_KEY,
      map: map.value
    });
    console.log('搜索服务初始化成功:', searchService.value);
  } catch (error) {
    console.error('初始化搜索服务失败:', error);
    // 延迟重试
    setTimeout(initSearchService, 2000);
  }
};

// 搜索地区
const searchLocation = (keyword) => {
  return new Promise((resolve, reject) => {
    if (!searchService.value) {
      reject(new Error('搜索服务未初始化'));
      return;
    }

    searchService.value.searchPlace({
      keyword: keyword,
      region: '全国',
      pageSize: 10,
      pageIndex: 1
    }).then((result) => {
      resolve(result.data);
    }).catch((error) => {
      reject(error);
    });
  });
};

// 根据坐标搜索地址
const searchAddressByCoords = (lat, lng) => {
  return new Promise((resolve, reject) => {
    if (!searchService.value) {
      reject(new Error('搜索服务未初始化'));
      return;
    }

    searchService.value.searchAddress({
      location: new TMap.LatLng(lat, lng)
    }).then((result) => {
      resolve(result.data);
    }).catch((error) => {
      reject(error);
    });
  });
};

// 绘制国家大剧院范围
const drawNationalGrandTheater = () => {
  if (!map.value || !window.TMap) {
    console.error('地图未初始化');
    return;
  }

  // 国家大剧院的大致坐标范围（椭圆形）
  const center = new TMap.LatLng(39.9069, 116.3974); // 国家大剧院中心坐标
  const radiusX = 0.001; // 东西方向半径
  const radiusY = 0.0008; // 南北方向半径

  // 生成椭圆形的点集
  const points = [];
  const segments = 32; // 分段数

  for (let i = 0; i <= segments; i++) {
    const angle = (i / segments) * 2 * Math.PI;
    const x = center.lng + radiusX * Math.cos(angle);
    const y = center.lat + radiusY * Math.sin(angle);
    points.push(new TMap.LatLng(y, x));
  }

  // 根据官方文档创建多边形
  const polygon = new TMap.MultiPolygon({
    map: map.value,
    styles: {
      'polygon': new TMap.PolygonStyle({
        color: 'rgba(255, 215, 0, 0.3)', // 金色半透明
        borderColor: '#FFD700', // 金色边框
        borderWidth: 2
      })
    },
    geometries: [{
      id: 'national-grand-theater',
      paths: [points]
    }]
  });

  // 保存到多边形数组
  polygons.value.push(polygon);

  // 添加标签
  const label = new TMap.MultiLabel({
    map: map.value,
    styles: {
      'label': new TMap.LabelStyle({
        color: '#FFD700',
        size: 16,
        offset: [0, -20],
        backgroundColor: 'rgba(0, 0, 0, 0.7)',
        borderColor: '#FFD700',
        borderWidth: 1,
        borderRadius: 4,
        padding: [4, 8]
      })
    },
    geometries: [{
      id: 'theater-label',
      position: center,
      content: '国家大剧院'
    }]
  });

  return { polygon, label };
};

// 绘制圆形范围（根据官方文档）
const drawCircle = (center, radius, options = {}) => {
  if (!map.value || !window.TMap) {
    console.error('地图未初始化');
    return null;
  }

  const defaultOptions = {
    id: `circle-${Date.now()}`,
    strokeColor: '#4A90E2',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#4A90E2',
    fillOpacity: 0.3
  };

  const circleOptions = { ...defaultOptions, ...options };

  // 使用官方文档的Circle API
  const circle = new TMap.Circle({
    map: map.value,
    center: new TMap.LatLng(center.lat, center.lng),
    radius: radius,
    strokeColor: circleOptions.strokeColor,
    strokeOpacity: circleOptions.strokeOpacity,
    strokeWeight: circleOptions.strokeWeight,
    fillColor: circleOptions.fillColor,
    fillOpacity: circleOptions.fillOpacity
  });

  // 保存到多边形数组
  polygons.value.push(circle);

  return circle;
};

// 绘制多边形范围
const drawPolygon = (polygonCoords, options = {}) => {
  if (!map.value || !window.TMap) {
    console.error('地图未初始化');
    return null;
  }

  const defaultOptions = {
    id: `polygon-${Date.now()}`,
    strokeColor: '#FF6B6B',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF6B6B',
    fillOpacity: 0.3,
    zIndex: 1
  };

  const polygonOptions = { ...defaultOptions, ...options };

  // 根据官方文档使用MultiPolygon
  const polygon = new TMap.MultiPolygon({
    map: map.value,
    styles: {
      'polygon': new TMap.PolygonStyle({
        color: polygonOptions.fillColor,
        opacity: polygonOptions.fillOpacity,
        borderColor: polygonOptions.strokeColor,
        borderWidth: polygonOptions.strokeWeight
      })
    },
    geometries: [{
      id: polygonOptions.id,
      paths: polygonCoords.map(coord => new TMap.LatLng(coord.lat, coord.lng))
    }]
  });

  polygons.value.push(polygon);

  return polygon;
};

// 添加标记点
const addMarker = (position, options = {}) => {
  if (!map.value || !window.TMap) {
    console.error('地图未初始化');
    return null;
  }

  const defaultOptions = {
    id: `marker-${Date.now()}`,
    title: '',
    icon: null,
    size: 32,
    color: '#FF6B6B',
    offset: [0, 0]
  };

  const markerOptions = { ...defaultOptions, ...options };

  const marker = new TMap.MultiMarker({
    map: map.value,
    styles: {
      'marker': new TMap.MarkerStyle({
        width: markerOptions.size,
        height: markerOptions.size,
        anchor: { x: 0.5, y: 1 },
        src: markerOptions.icon || ''
      })
    },
    geometries: [{
      id: markerOptions.id,
      position: new TMap.LatLng(position.lat, position.lng),
      title: markerOptions.title
    }]
  });

  // 保存到标记数组
  markers.value.push(marker);

  return marker;
};

// 批量添加标记点
const addMarkers = (markerList) => {
  if (!Array.isArray(markerList)) {
    console.error('标记点列表必须是数组');
    return [];
  }

  return markerList.map(item => {
    return addMarker(item.position, item.options);
  });
};

// 移除标记点
const removeMarker = (markerId) => {
  const index = markers.value.findIndex(marker =>
    marker.geometries[0]?.id === markerId
  );

  if (index > -1) {
    markers.value[index].setMap(null);
    markers.value.splice(index, 1);
  }
};

// 清除所有标记点
const clearMarkers = () => {
  markers.value.forEach(marker => {
    marker.setMap(null);
  });
  markers.value = [];
};

// 绘制路径
const drawPath = (pathCoords, options = {}) => {
  if (!map.value || !window.TMap) {
    console.error('地图未初始化');
    return null;
  }

  const defaultOptions = {
    id: `path-${Date.now()}`,
    strokeColor: '#4A90E2',
    strokeOpacity: 0.8,
    strokeWeight: 4,
    strokeStyle: 'solid',
    zIndex: 2
  };

  const pathOptions = { ...defaultOptions, ...options };

  // 转换坐标格式
  const points = pathCoords.map(coord => new TMap.LatLng(coord.lat, coord.lng));

  const path = new TMap.MultiPolyline({
    map: map.value,
    styles: {
      'path': new TMap.PolylineStyle({
        color: pathOptions.strokeColor,
        width: pathOptions.strokeWeight,
        opacity: pathOptions.strokeOpacity,
        lineStyle: pathOptions.strokeStyle === 'dashed' ? 'dashed' : 'solid'
      })
    },
    geometries: [{
      id: pathOptions.id,
      paths: points
    }]
  });

  // 保存到路径数组
  paths.value.push(path);

  return path;
};

// 绘制多条路径
const drawPaths = (pathsList) => {
  if (!Array.isArray(pathsList)) {
    console.error('路径列表必须是数组');
    return [];
  }

  return pathsList.map(item => {
    return drawPath(item.coords, item.options);
  });
};

// 移除路径
const removePath = (pathId) => {
  const index = paths.value.findIndex(path =>
    path.geometries[0]?.id === pathId
  );

  if (index > -1) {
    paths.value[index].setMap(null);
    paths.value.splice(index, 1);
  }
};

// 清除所有路径
const clearPaths = () => {
  paths.value.forEach(path => {
    path.setMap(null);
  });
  paths.value = [];
};

// 地图控制功能
const flyTo = (position, zoom = 15, duration = 1000) => {
  if (!map.value) {
    console.error('地图未初始化');
    return;
  }

  map.value.flyTo({
    center: new TMap.LatLng(position.lat, position.lng),
    zoom: zoom,
    duration: duration
  });
};

const setCenter = (position) => {
  if (!map.value) {
    console.error('地图未初始化');
    return;
  }

  map.value.setCenter(new TMap.LatLng(position.lat, position.lng));
};

const setZoom = (zoom) => {
  if (!map.value) {
    console.error('地图未初始化');
    return;
  }

  map.value.setZoom(zoom);
};

// 清除所有图层
const clearAll = () => {
  console.log('=== 开始清除所有图层 ===');
  console.log('清除前标记数量:', markers.value.length);
  console.log('清除前路径数量:', paths.value.length);
  console.log('清除前多边形数量:', polygons.value.length);

  try {
    clearMarkers();
    clearPaths();
    polygons.value.forEach(polygon => {
      polygon.setMap(null);
    });
    polygons.value = [];

    console.log('=== 清除完成 ===');
    console.log('清除后标记数量:', markers.value.length);
    console.log('清除后路径数量:', paths.value.length);
    console.log('清除后多边形数量:', polygons.value.length);
  } catch (error) {
    console.error('清除图层时发生错误:', error);
    console.error('错误堆栈:', error.stack);
  }
};

// 获取地图当前状态
const getMapState = () => {
  if (!map.value) {
    return null;
  }

  return {
    center: map.value.getCenter(),
    zoom: map.value.getZoom(),
    bounds: map.value.getBounds(),
    markers: markers.value.length,
    paths: paths.value.length,
    polygons: polygons.value.length
  };
};

// 导出地图为图片
const exportMapImage = () => {
  if (!map.value) {
    console.error('地图未初始化');
    return null;
  }

  return new Promise((resolve, reject) => {
    try {
      const canvas = map.value.getCanvas();
      const dataURL = canvas.toDataURL('image/png');
      resolve(dataURL);
    } catch (error) {
      reject(error);
    }
  });
};

</script>

<style scoped>
.map-container {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
}

.map-inner {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
}

/* 加载状态样式 */
.map-loading {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.98) 0%, rgba(248, 250, 252, 0.95) 100%);
  backdrop-filter: blur(10px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.loading-spinner {
  text-align: center;
  animation: fadeInUp 0.8s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}

.wave-spinner {
  position: relative;
  width: 120px;
  height: 120px;
  margin: 0 auto 20px;
  filter: drop-shadow(0 0 30px rgba(74, 144, 226, 0.2));
}

.wave-ring {
  position: absolute;
  top: 50%;
  left: 50%;
  border: 2px solid transparent;
  border-radius: 50%;
  transform: translate(-50%, -50%);
  opacity: 0;
  box-shadow: 0 0 20px rgba(74, 144, 226, 0.3);
}

.wave-1 {
  width: 40px;
  height: 40px;
  border-color: #4a90e2;
  background: linear-gradient(45deg, rgba(74, 144, 226, 0.1), rgba(74, 144, 226, 0.05));
  animation: waveExpand 2.5s cubic-bezier(0.25, 0.46, 0.45, 0.94) infinite;
}

.wave-2 {
  width: 60px;
  height: 60px;
  border-color: #5ba0f2;
  background: linear-gradient(45deg, rgba(91, 160, 242, 0.08), rgba(91, 160, 242, 0.03));
  animation: waveExpand 2.5s cubic-bezier(0.25, 0.46, 0.45, 0.94) infinite 0.4s;
}

.wave-3 {
  width: 80px;
  height: 80px;
  border-color: #6cb0ff;
  background: linear-gradient(45deg, rgba(108, 176, 255, 0.06), rgba(108, 176, 255, 0.02));
  animation: waveExpand 2.5s cubic-bezier(0.25, 0.46, 0.45, 0.94) infinite 0.8s;
}

.wave-4 {
  width: 100px;
  height: 100px;
  border-color: #7dc0ff;
  background: linear-gradient(45deg, rgba(125, 192, 255, 0.04), rgba(125, 192, 255, 0.01));
  animation: waveExpand 2.5s cubic-bezier(0.25, 0.46, 0.45, 0.94) infinite 1.2s;
}

.loading-text {
  color: #4a90e2;
  font-size: 14px;
  font-weight: 500;
  letter-spacing: 2px;
  margin-top: 80px;
  text-shadow: 0 0 10px rgba(74, 144, 226, 0.3);
  animation: textPulse 2s ease-in-out infinite;
}

@keyframes waveExpand {
  0% {
    transform: translate(-50%, -50%) scale(0.2);
    opacity: 0.8;
  }

  50% {
    opacity: 0.4;
  }

  100% {
    transform: translate(-50%, -50%) scale(1.8);
    opacity: 0;
  }
}

@keyframes textPulse {

  0%,
  100% {
    opacity: 0.8;
    transform: scale(1);
  }

  50% {
    opacity: 1;
    transform: scale(1.05);
  }
}

@keyframes fadeInUp {
  0% {
    opacity: 0;
    transform: translateY(20px);
  }

  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

/* Vue过渡动画 - 淡入淡出 */
.loading-fade-enter-active {
  transition: all 0.6s ease-out;
}

.loading-fade-leave-active {
  transition: all 0.4s ease-in;
}

.loading-fade-enter-from {
  opacity: 0;
  transform: translateY(15px);
}

.loading-fade-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}

/* 等待提示样式 */
.waiting-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.7);
  backdrop-filter: blur(8px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.waiting-content {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 40px;
  text-align: center;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
  max-width: 400px;
  width: 90%;
}

.waiting-spinner {
  position: relative;
  width: 80px;
  height: 80px;
  margin: 0 auto 20px;
}

.spinner-ring {
  position: absolute;
  top: 50%;
  left: 50%;
  border: 3px solid transparent;
  border-radius: 50%;
  transform: translate(-50%, -50%);
  animation: spin 1.5s linear infinite;
}

.spinner-ring:nth-child(1) {
  width: 60px;
  height: 60px;
  border-top-color: #2196F3;
  animation-delay: 0s;
}

.spinner-ring:nth-child(2) {
  width: 40px;
  height: 40px;
  border-top-color: #4CAF50;
  animation-delay: 0.2s;
}

.spinner-ring:nth-child(3) {
  width: 20px;
  height: 20px;
  border-top-color: #FF9800;
  animation-delay: 0.4s;
}

.waiting-text {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 20px;
}

.waiting-progress {
  width: 100%;
  height: 6px;
  background: #e0e0e0;
  border-radius: 3px;
  overflow: hidden;
}

.progress-bar {
  height: 100%;
  background: linear-gradient(90deg, #2196F3, #4CAF50);
  border-radius: 3px;
  transition: width 0.3s ease;
}

@keyframes spin {
  0% {
    transform: translate(-50%, -50%) rotate(0deg);
  }

  100% {
    transform: translate(-50%, -50%) rotate(360deg);
  }
}

/* Vue过渡动画 - 等待提示淡入淡出 */
.waiting-fade-enter-active {
  transition: all 0.4s ease-out;
}

.waiting-fade-leave-active {
  transition: all 0.3s ease-in;
}

.waiting-fade-enter-from {
  opacity: 0;
  transform: scale(0.9);
}

.waiting-fade-leave-to {
  opacity: 0;
  transform: scale(1.1);
}
</style>